-- UIMonsterCaptainEquip
-- Created by zouyb Dec/30/2015
-- 海怪船长装备描述界面

UIMonsterCaptainEquip = class("UIMonsterCaptainEquip", function()
    return cc.Layer:create();
end);

function UIMonsterCaptainEquip.create(itemId, pos, index)
    return UIMonsterCaptainEquip.new(itemId, pos, index);
end

function UIMonsterCaptainEquip:ctor(itemId, pos, index)
    -- 初始化
    self:setName("UIMonsterCaptainEquip");
	-- 重用魔藤技能学习界面
    local node = cc.CSLoader:createNode("layout/bine/BineSkillLearn.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    self.itemId = itemId;  -- 装备ID
	self.pos = pos;        -- 格子坐标
	self.index = index;    -- 装备索引(1-3)

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIMonsterCaptainEquip:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIMonsterCaptainEquip:registerEventCallback()
    -- 关注喂食后的事件
    EventMgr.register("UIMonsterCaptainEquip", event.FEED_MONSTER_CAPTAIN, function(args)
        self:whenFeedCaptain(args);
    end);

    EventMgr.register("UIMonsterCaptainEquip", event.GAIN_PET, function(args)
        -- 获得冈布奥了，关闭本界面
        UIMgr.getCurrentScene():removeFormByName("UIMonsterCaptainEquip");
        UIMgr.getCurrentScene():removeFormByName("UIMonsterCaptain");
    end);

    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIMonsterCaptainEquip 界面析构清理");

            -- 移除所有事件关注
            EventMgr.removeAll("UIMonsterCaptainEquip");
        end
    end);
end

-- 注册点击事件
function UIMonsterCaptainEquip:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIMonsterCaptainEquip");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_select");
            -- 尝试装备
            self:tryEquip();
        end
    end
    btnOk:addTouchEventListener(onOkClick);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_equip"));
end

-- 重绘
function UIMonsterCaptainEquip:redraw()
    -- 名称
    local nameLabel = findChildByName(self.node, "CT/name");
    local itemName = ItemM.query(self.itemId, "name");
    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    nameLabel:setString(itemName);

    local descLabel = findChildByName(self.node, "CT/desc");
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local desc = "";

    if self.index < 4 then
        local grid = DungeonM.getGridByPos(self.pos);

        -- 是否已经装备了
        local function isEquiped()
            local list = grid.summon.equipments or {};
            for _, id in pairs(list) do
                if id == self.itemId then
                    return true;
                end
            end

            return false;
        end

        desc = ItemM.query(self.itemId, "desc") .. "\n\n";
        desc = desc .. getLocStr("monster_captain_hint1") .. "\n\n";

        if isEquiped() then
            desc = desc .. "[blue]" .. ItemM.query(self.itemId, "detail") .. "[-]";
        else
            desc = desc .. "[gray]" .. ItemM.query(self.itemId, "detail") .. "[-]";
        end


        if isEquiped() then
            setButtonEnabled(btnOk, false);
        else
            setButtonEnabled(btnOk, true);
        end
    else
        nameLabel:setString(getLocStr("monster_captain_stomach_name"));

        -- 戴维琼斯的胃，特殊处理显示界面
        desc = getLocStr("monster_captain_stomach_desc") .. "\n\n";
        desc = desc .. getLocStr("monster_captain_hint2") .. "\n\n";

        -- 显示各种属性加成
        local props = MonsterCaptainM.getFoodProps(self.pos);

        -- 按要求顺序排列一下
        local list = { ["attack"] = 1, ["magic"] = 2, ["hp"] = 3, ["mp"] = 4, ["cannon"] = 5 };

        local function sortProp(p1, p2)
            return list[p1[2]] < list[p2[2]];
        end
        table.sort(props, sortProp);

        for i, prop in pairs(props) do
            desc = desc .. "[blue]" .. extractString(PropM.getPropDesc(prop)) .. "[-]";

            if i ~= #props then
                desc = desc .. "\n";
            end
        end

        -- 按钮显示"喂食"
        btnOk:setTitleText(getLocStr("btn_text_feed"));
    end

    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel = applyString(descLabel, desc);

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL, { nameLabel, descLabel, btnOk});
end

-- 尝试装备
function UIMonsterCaptainEquip:tryEquip()
    if self.index == 4 then
        -- 进行喂食的物品列表
        local submitList = MonsterCaptainM.getAllFeedItems();
        -- 打开装备选择界面
        local uiEquip = UIEquips.create(EQUIP_OPEN_TYPE_MONSTER_CAPTAIN, {["index"] = self.index, ["submited"] = submitList,});
        UIMgr.getCurrentScene():addForm(uiEquip);
        return;
    end

    if ItemM.getAmount(ME.user, self.itemId) <= 0 then
		-- 消耗不足
		local name = ItemM.query(self.itemId, "name");

		alert(string.format(getLocStr("item_not_enough"), name));
        return;
    end

    -- 装备
    if DungeonActionM.go("submit_monster_captain", self.pos, self.itemId) then
		local uiForm = UIMgr.getCurrentScene():getFormByName("UIMonsterCaptain");
		uiForm:onEquip(self.index);

		-- 关闭界面
        UIMgr.getCurrentScene():removeFormByName("UIMonsterCaptainEquip");
	end
end

-- 喂食处理
function UIMonsterCaptainEquip:whenFeedCaptain(args)
    local pos = args.pos;
    local grid = DungeonM.getGridByPos(pos);

    -- 喂食完之后可能这个界面就要关掉了
    if grid.state == GRID_STATE_DISABLE then
        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UIMonsterCaptainEquip");
        return;
    end

    -- 界面重绘下
    self:redraw();
end

